package com.phiture.erp.basic.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.basic.core.pojo.dto.ErpAccountPageReqDTO;
import com.phiture.erp.basic.core.pojo.dto.ErpAccountSaveReqDTO;
import com.phiture.erp.basic.core.service.ErpAccountService;
import com.phiture.erp.basic.dal.entity.ErpAccountDO;
import com.phiture.erp.basic.dal.mapper.ErpAccountMapper;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.utils.ErpNoGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static com.phiture.erp.common.constants.ErrorCodeConstants.ACCOUNT_NOT_ENABLE;
import static com.phiture.erp.common.constants.ErrorCodeConstants.ACCOUNT_NOT_EXISTS;

/**
 * @author YH
 * @date 2025/3/31
 */

@Service
@RequiredArgsConstructor
public class ErpAccountServiceImpl implements ErpAccountService {
    private final ErpAccountMapper accountMapper;
    private final ErpNoGenerator erpNoGenerator;

    @Override
    public Long createAccount(ErpAccountSaveReqDTO createReqDTO) {
        // 插入
        ErpAccountDO account = BeanUtils.toBean(createReqDTO, ErpAccountDO.class);
        String no = erpNoGenerator.generate(ErpNoPrefixConstants.MRP_ACCOUNT_NO_PREFIX);
        account.setNo(no);

        accountMapper.insert(account);
        // 返回
        return account.getId();
    }

    @Override
    public void updateAccount(ErpAccountSaveReqDTO updateReqDTO) {
        // 校验存在
        validateAccountExists(updateReqDTO.getId());
        // 更新
        ErpAccountDO updateObj = BeanUtils.toBean(updateReqDTO, ErpAccountDO.class);
        accountMapper.updateById(updateObj);
    }

    @Override
    public void updateAccountDefaultStatus(Long id, Boolean defaultStatus) {
        // 1. 校验存在
        validateAccountExists(id);

        // 2.1 如果开启，则需要关闭所有其它的默认
        if (defaultStatus) {
            ErpAccountDO account = accountMapper.selectOne(ErpAccountDO::getDefaultStatus, true);
            if (account != null) {
                accountMapper.updateById(new ErpAccountDO().setId(account.getId()).setDefaultStatus(false));
            }
        }
        // 2.2 更新对应的默认状态
        accountMapper.updateById(new ErpAccountDO().setId(id).setDefaultStatus(defaultStatus));
    }

    @Override
    public void deleteAccount(Long id) {
        // 校验存在
        validateAccountExists(id);
        // 删除
        accountMapper.deleteById(id);
    }

    @Override
    public ErpAccountDO getAccount(Long id) {
        return accountMapper.selectById(id);
    }

    @Override
    public ErpAccountDO validateAccount(Long id) {
        ErpAccountDO account = accountMapper.selectById(id);
        if (account == null) {
            throw exception(ACCOUNT_NOT_EXISTS);
        }
        if (CommonStatusEnum.isDisable(account.getStatus())) {
            throw exception(ACCOUNT_NOT_ENABLE, account.getName());
        }
        return account;
    }

    @Override
    public List<ErpAccountDO> getAccountListByStatus(Integer status) {
        return accountMapper.selectList(ErpAccountDO::getStatus, status);
    }

    @Override
    public List<ErpAccountDO> getAccountList(Collection<Long> ids) {
        return accountMapper.selectBatchIds(ids);
    }

    @Override
    public Map<Long, ErpAccountDO> getAccountMap(Collection<Long> ids) {
        return convertMap(getAccountList(ids), ErpAccountDO::getId);
    }

    @Override
    public PageResult<ErpAccountDO> getAccountPage(ErpAccountPageReqDTO pageReqDTO) {
        return accountMapper.selectPage(pageReqDTO, new LambdaQueryWrapperX<ErpAccountDO>()
                .likeIfPresent(ErpAccountDO::getName, pageReqDTO.getName())
                .likeIfPresent(ErpAccountDO::getNo, pageReqDTO.getNo())
                .eqIfPresent(ErpAccountDO::getRemark, pageReqDTO.getRemark())
                .orderByDesc(ErpAccountDO::getId));
    }

    @Override
    public Map<Long, KeyValue<String, Boolean>> getAccountMap() {
        List<ErpAccountDO> list = accountMapper.selectList(
                Wrappers.lambdaQuery(ErpAccountDO.class)
                        .eq(ErpAccountDO::getDeleted, Boolean.FALSE)
                        .eq(ErpAccountDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                        .orderByDesc(ErpAccountDO::getDefaultStatus)
        );
        return CollUtil.isEmpty(list)
                ? Collections.emptyMap()
                : list.stream().collect(Collectors.toMap(ErpAccountDO::getId, item -> new KeyValue<>(item.getName(), item.getDefaultStatus())));
    }

    @Override
    public ErpAccountDO getDefaultAccount() {
        return accountMapper.selectOne(ErpAccountDO::getDefaultStatus, Boolean.TRUE);
    }

    private void validateAccountExists(Long id) {
        if (accountMapper.selectById(id) == null) {
            throw exception(ACCOUNT_NOT_EXISTS);
        }
    }
}
